package com.placement.app.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.placement.app.forms.MainSearchForm;
import com.placement.app.model.JobData;
import com.placement.app.model.ZipLocation;
import com.placement.app.service.JobService;
import com.placement.app.service.LocationService;


public class MainSearchAction extends BaseAction {
	private static final Log logger = LogFactory.getLog(MainSearchAction.class);
	
	private LocationService locationService= null;
	private JobService jobService=null;
	/**
	 * @return the jobService
	 */
	public JobService getJobService() {
		return jobService;
	}
	/**
	 * @param jobService the jobService to set
	 */
	public void setJobService(JobService jobService) {
		this.jobService = jobService;
	}
	/**
	 * Purpose: This method search for the job specified by the user
	 * 			in database 
	 * 
	 * @param mapping		:ActionMapping object
	 * @param form			:ActionForm object
	 * @param request		:HttpServletRequest object
	 * @param response		:HttpServletResponse object
	 * @return				:ActionForward object
	 */
	public ActionForward find(ActionMapping mapping,ActionForm form,
							HttpServletRequest request,HttpServletResponse response){
		
		String forward="search";
		MainSearchForm mForm = (MainSearchForm)form;
		String location = mForm.getLocation()==null ? "" : mForm.getLocation().trim();
		String searchString = mForm.getSearchString()==null ? "": mForm.getSearchString().trim();
		String newSearch = searchString + " - "+ location;
		if(mForm.getPrevSearch().size()==0 
				|| (mForm.getPrevSearch().get(0) != null
				&& !mForm.getPrevSearch().get(0).equals(newSearch)))
			mForm.getPrevSearch().add(0, newSearch);
		while(mForm.getPrevSearch().size()>5){
			mForm.getPrevSearch().remove(mForm.getPrevSearch().size()-1);
		}
		mForm.setSearchResults(null);
		ZipLocation zipcode = locationService.getLocation(location);
		//ArrayList<ZipLocation> list = locationService.getZipCodesInRange(zipcode, 5);
		List<JobData> jobResult = jobService.getJobList(searchString, zipcode, 35);
		if(jobResult != null){
			logger.debug("jobResults Length: " +jobResult.size());
			if(jobResult.size()>0){
				mForm.setSearchResults(jobResult);
				request.setAttribute("SEARCH_STRING", searchString);
				request.setAttribute("LOCATION", zipcode);
				forward = "listResult";
			}
		}
		return mapping.findForward(forward);
	}
	public LocationService getLocationService() {
		return locationService;
	}
	public void setLocationService(LocationService locationService) {
		this.locationService = locationService;
	}
	
	
}
